package br.edu.ifrn.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.edu.ifrn.beans.Aluno;
import br.edu.ifrn.beans.Egresso;
import br.edu.ifrn.persistencia.AlunoDAO;
import br.edu.ifrn.persistencia.EgressoDAO;

public class AdminListar extends HttpServlet {
	private static final long serialVersionUID = 1L;
       HttpSession sessao;
       EgressoDAO egressoDao = new EgressoDAO();
       AlunoDAO alunoDao = new AlunoDAO();
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		sessao = req.getSession();
		getEgressos(req, resp);
	}

	private void getEgressos(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String nome = req.getParameter("nome");
		String mat = req.getParameter("matricula");
		List<Egresso> egressos = new ArrayList<Egresso>();
		if(!mat.equals("")){
			Egresso egresso = egressoDao.recuperarPorMatricula(mat);
			egressos.add(egresso);
		}else if(!nome.equals("")){
			egressos = egressoDao.listarEgressosPorNome(nome); 
		}else{
			egressos = egressoDao.listarEgressos();
		}
		sessao.setAttribute("egressos", egressos);
		RequestDispatcher jsp = req.getRequestDispatcher("listaregressos.jsp");
		jsp.forward(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		sessao = req.getSession();
		sessao.removeAttribute("alunos");
		getAlunos(req, resp);
	}
	
	private void getAlunos(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String nome = req.getParameter("nome");
		String mat = req.getParameter("matricula");
		List<Aluno> alunos = new ArrayList<Aluno>();
		
		if(!mat.equals("")){
			Aluno aluno = alunoDao.recuperarPorMatricula(mat);
			alunos.add(aluno);
		} else if(!nome.equals("")){
			alunos = alunoDao.listarAlunosPorNome(nome);
		} else{
			alunos = alunoDao.listarAlunos();
		}
		sessao.setAttribute("alunos", alunos);
		RequestDispatcher jsp = req.getRequestDispatcher("listaralunos.jsp");
		jsp.forward(req, resp);
	}
	

}
